parties <- c("Democratic Unionist Party (DUP)",
             "Conservative Party",
             "Labour Party",
             "Liberal Democrats",
             "Social Democratic and Labour Party (SDLP)",
             "Scottish National Party (SNP)",
             "Plaid Cymru",
             "UK Independence Party (UKIP)",
             "Green Party of England and  Wales",
             "Sinn Fein",
             "Ulster Unionist Party (UUP)",
             "Alliance Party of Northern Ireland",
             "Other Party",
             "No - none",
             "Dont Know")

qual.data$voteint.2 <- qual.data$voteint - 99
qual.data$voteint.2[which(qual.data$voteint.2 <= 0)] <- 
  qual.data$voteint.2[which(qual.data$voteint.2 <= 0)] + 14
table(qual.data$voteint.2)

vote.levels <- c("Democratic Unionist Party (DUP)",
                 "Conservative",
                 "Labour",
                 "Liberal Democrats",
                 "Social Democratic and Labour Party (SDLP)",
                 "Scottish National Party",
                 "Plaid Cymru",
                 "UK Independence Party",
                 "Greens",
                 "Sinn Fein",
                 "Ulster Unionist Party (UUP)",
                 "Alliance Party of Northern Ireland",
                 "Not intend to vote",
                 "I have not made up my mind yet")
# fig_path <- "figs/by_voteint"
use.data.2 <- merge(use.data, qual.data[, c("psid","voteint.2")], 
                    by.x = "psid", by.y = "psid")

process_eachitem_party <- function(x){
  estimates <- data.frame(rbind(rep(NA, 2), t(x)))
}

amce_plot_data_by_party <- list()
for(j in 1:6){
  i <- c(2,3,4,6,8,9)[j]
  party <- c("Cons", "Lab", "LibDem", "SNP", "UKIP", "Greens")[j]

  if(!exists("use_weight") || use_weight == F) {
    results <- amce(Chosen_party ~ Economy + Jobs + Immigration + EU + Education,
                    data = use.data.2[ which(use.data.2$voteint.2 == i), ], 
                    design = ukdesign, 
                    cluster=F)
  } else {
    results <- amce(Chosen_party ~ Economy + Jobs + Immigration + EU + Education,
                    data = use.data.2[ which(use.data.2$voteint.2 == i), ], 
                    design = ukdesign, 
                    weight = "weight",
                    cluster=F)
    
  }
    
  temp <- lapply(results$estimates, process_eachitem_party)
  amce_plot_data <- rbindlist(temp)
  names(amce_plot_data)[2] <- "se"
  amce_plot_data$y <- nrow(amce_plot_data):1
  amce_plot_data$texts <- factor(nrow(amce_plot_data):1, labels = rev(att.data2[, 2]))
  amce_plot_data$party <- j
  amce_plot_data_by_party[[party]] <- amce_plot_data
}
amce_plot_data_by_party <- rbindlist(amce_plot_data_by_party)
amce_plot_data_by_party$party <- factor(amce_plot_data_by_party$party,
                                        labels = c("Cons", "Lab", "LibDem", "SNP", "UKIP", "Greens"))
colours <- brewer.pal(7, "Set1")[c(2,1,7,5,4,3)]

repeat.before <- function(x) {   # repeats the last non NA value. Keeps leading NA
  ind = which(!is.na(x))      # get positions of nonmissing values
  if(is.na(x[1]))             # if it begins with a missing, add the 
    ind = c(1,ind)        # first position to the indices
  rep(x[ind], times = diff(   # repeat the values at these indices
    c(ind, length(x) + 1) )) # diffing the indices + length yields how often 
}                               # they need to be repeated

amce_plot_data_by_party_3 <- amce_plot_data_by_party %>%
  mutate(attribute = stri_extract_first_regex(texts, "(.+):") %>% 
           stri_replace_all_fixed(":", "") %>% repeat.before()) %>%
  filter(!is.na(AMCE))
levels(amce_plot_data_by_party_3$texts) <- 
  levels(amce_plot_data_by_party_3$texts) %>%
  stri_trim_both() %>% stri_replace_all_fixed("skilled migrants.", "skilled migrants.\n")


g <- ggplot(amce_plot_data_by_party_3, aes(y = AMCE, x = texts, group = party,
                                           colour = party)) + 
  geom_hline(yintercept = 0, size = 1, color = "grey90") + 
  geom_linerange(aes(ymin = AMCE - 1.96 * se,
                     ymax = AMCE + 1.96 * se),
                 position = position_dodge(width = .6),
                 colour = "grey60",
                 size = .4) + 
  geom_point(position = position_dodge(width = .6), aes(shape = party), 
             size = 2) + 
  ylab("AMCE") + xlab("") + 
  theme(legend.position = "bottom", #axis.text.y = element_text(hjust = 0),
        legend.direction = "horizontal", legend.title=element_blank(),
        axis.text=element_text(size=12.5))+
  scale_color_manual(values=as.character(colours)) +
  facet_grid(attribute ~., scales = "free", space = "free") + 
  scale_shape_manual(values = c(15:17, 0:2)) + 
  coord_flip()
